package com.zsd.android.opencvface.view.activity;

import android.Manifest;
import android.os.Bundle;
import android.os.Environment;
import android.util.Size;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import com.zsd.android.opencvface.OpenCVJni;
import com.zsd.android.opencvface.R;
import com.zsd.android.opencvface.utils.CameraHelper;
import com.zsd.android.opencvface.utils.FileUtil;
import com.zsd.android.opencvface.utils.PermissionHelper;

import java.io.File;

public class FaceActivity extends BaseActivity implements View.OnClickListener, CameraHelper.PreviewCallback {

    private SurfaceView mSurfaceView;

    private OpenCVJni openCVJni;
    private CameraHelper cameraHelper;
    private long changeTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face);

        mSurfaceView = findViewById(R.id.surface_view);
        findViewById(R.id.change_btn).setOnClickListener(this);

        PermissionHelper.getInstance(this).isPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        FileUtil.copyAssets(this, "lbpcascade_frontalface.xml");
        openCVJni = new OpenCVJni();
        cameraHelper = new CameraHelper(this);
        cameraHelper.setPreviewCallback(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String path = new File(Environment.getExternalStorageDirectory(), "lbpcascade_frontalface.xml").getAbsolutePath();
        cameraHelper.setSurfaceHolder(mSurfaceView.getHolder());
        openCVJni.init(path);
    }

    @Override
    protected void onPause() {
        super.onPause();
        cameraHelper.stopBackgroundThread();
        cameraHelper.closeCamera();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.change_btn:
                long currentTimeMillis = System.currentTimeMillis();
                if (currentTimeMillis - changeTime >= 1500) {
                    cameraHelper.changeCamera();
                    changeTime = currentTimeMillis;
                }
                break;
        }
    }

    private boolean isTrue = true;

    @Override
    public void onPreviewFrame(byte[] data, Size mPreviewSize, String cameraId) {
//        if (isTrue) {
//            isTrue = false;
//            openCVJni.postData(data, mPreviewSize.getWidth(), mPreviewSize.getHeight(), Integer.parseInt(cameraId));
//        }
        openCVJni.postData(data, mPreviewSize.getWidth(), mPreviewSize.getHeight(), Integer.parseInt(cameraId));
    }

    @Override
    public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        openCVJni.setSurface(holder.getSurface());
    }
}
